package com.lifeverse.service;

import com.lifeverse.entity.KnowledgeBase;
import com.lifeverse.entity.LearningExperience;
import com.lifeverse.entity.enums.KnowledgeStatus;
import com.lifeverse.entity.enums.KnowledgeType;
import com.lifeverse.repository.KnowledgeBaseRepository;
import com.lifeverse.repository.LearningExperienceRepository;
import com.lifeverse.util.JsonUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 知识管理服务
 * 负责知识的创建、存储、检索、更新和维护
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class KnowledgeManagementService {

    private final KnowledgeBaseRepository knowledgeBaseRepository;
    private final LearningExperienceRepository learningExperienceRepository;
    private final JsonUtils jsonUtils;

    /**
     * 从学习经验中提取知识
     */
    @Transactional
    public List<KnowledgeBase> extractKnowledgeFromExperience(LearningExperience experience) {
        log.info("从学习经验 {} 中提取知识", experience.getId());
        
        List<KnowledgeBase> extractedKnowledge = new ArrayList<>();
        
        try {
            // 1. 提取程序性知识
            KnowledgeBase proceduralKnowledge = extractProceduralKnowledge(experience);
            if (proceduralKnowledge != null) {
                extractedKnowledge.add(proceduralKnowledge);
            }
            
            // 2. 提取概念性知识
            KnowledgeBase conceptualKnowledge = extractConceptualKnowledge(experience);
            if (conceptualKnowledge != null) {
                extractedKnowledge.add(conceptualKnowledge);
            }
            
            // 3. 提取策略性知识
            KnowledgeBase strategicKnowledge = extractStrategicKnowledge(experience);
            if (strategicKnowledge != null) {
                extractedKnowledge.add(strategicKnowledge);
            }
            
            // 4. 提取条件性知识
            KnowledgeBase conditionalKnowledge = extractConditionalKnowledge(experience);
            if (conditionalKnowledge != null) {
                extractedKnowledge.add(conditionalKnowledge);
            }
            
            // 保存提取的知识
            if (!extractedKnowledge.isEmpty()) {
                extractedKnowledge = knowledgeBaseRepository.saveAll(extractedKnowledge);
                log.info("从经验中成功提取 {} 个知识点", extractedKnowledge.size());
            }
            
        } catch (Exception e) {
            log.error("从学习经验中提取知识失败", e);
        }
        
        return extractedKnowledge;
    }

    /**
     * 创建新知识
     */
    @Transactional
    public KnowledgeBase createKnowledge(Long lifeEntityId, Map<String, Object> knowledgeData) {
        log.info("为生命体 {} 创建新知识", lifeEntityId);
        
        try {
            KnowledgeBase knowledge = new KnowledgeBase();
            knowledge.setLifeEntityId(lifeEntityId);
            
            // 设置基本信息
            knowledge.setKnowledgeType(parseKnowledgeType(knowledgeData));
            knowledge.setTitle((String) knowledgeData.getOrDefault("title", "未命名知识"));
            knowledge.setContent((String) knowledgeData.get("content"));
            knowledge.setSummary((String) knowledgeData.get("summary"));
            knowledge.setTags((String) knowledgeData.get("tags"));
            knowledge.setCategory((String) knowledgeData.get("category"));
            
            // 设置状态和评分
            knowledge.setStatus(KnowledgeStatus.LEARNING);
            knowledge.setConfidence(parseDouble(knowledgeData, "confidence", 0.5));
            knowledge.setImportance(parseDouble(knowledgeData, "importance", 0.5));
            knowledge.setUsageFrequency(0);
            
            // 设置其他属性
            knowledge.setSource((String) knowledgeData.get("source"));
            knowledge.setPrerequisites((String) knowledgeData.get("prerequisites"));
            knowledge.setDepthLevel(parseInt(knowledgeData, "depth_level", 1));
            knowledge.setAbstractionLevel(parseDouble(knowledgeData, "abstraction_level", 0.5));
            knowledge.setKnowledgeVersion(1);
            
            // 设置扩展属性
            Map<String, Object> metadata = createKnowledgeMetadata(knowledgeData);
            knowledge.setMetadata(jsonUtils.toJson(metadata));
            
            // 保存知识
            knowledge = knowledgeBaseRepository.save(knowledge);
            
            // 建立知识关联
            establishKnowledgeRelations(knowledge);
            
            log.info("成功创建知识，ID: {}", knowledge.getId());
            return knowledge;
            
        } catch (Exception e) {
            log.error("创建知识失败", e);
            throw new RuntimeException("创建知识失败: " + e.getMessage());
        }
    }

    /**
     * 搜索知识
     */
    public List<KnowledgeBase> searchKnowledge(Long lifeEntityId, String keyword, KnowledgeSearchCriteria criteria) {
        log.info("为生命体 {} 搜索知识，关键词: {}", lifeEntityId, keyword);
        
        try {
            List<KnowledgeBase> results = new ArrayList<>();
            
            if (keyword != null && !keyword.trim().isEmpty()) {
                // 全文搜索
                results = knowledgeBaseRepository.searchKnowledge(lifeEntityId, keyword);
            } else {
                // 获取所有知识
                results = knowledgeBaseRepository.findByLifeEntityId(lifeEntityId);
            }
            
            // 应用搜索条件过滤
            if (criteria != null) {
                results = applySearchCriteria(results, criteria);
            }
            
            // 按相关性排序
            results = sortByRelevance(results, keyword);
            
            log.info("搜索完成，找到 {} 个相关知识", results.size());
            return results;
            
        } catch (Exception e) {
            log.error("搜索知识失败", e);
            return new ArrayList<>();
        }
    }

    /**
     * 更新知识
     */
    @Transactional
    public KnowledgeBase updateKnowledge(Long knowledgeId, Map<String, Object> updateData) {
        log.info("更新知识 {}", knowledgeId);
        
        try {
            KnowledgeBase knowledge = knowledgeBaseRepository.findById(knowledgeId)
                    .orElseThrow(() -> new RuntimeException("知识不存在"));
            
            // 创建新版本
            if (shouldCreateNewVersion(knowledge, updateData)) {
                return createNewKnowledgeVersion(knowledge, updateData);
            }
            
            // 更新现有知识
            updateKnowledgeFields(knowledge, updateData);
            
            // 重新评估知识
            reevaluateKnowledge(knowledge);
            
            knowledge = knowledgeBaseRepository.save(knowledge);
            
            log.info("成功更新知识 {}", knowledgeId);
            return knowledge;
            
        } catch (Exception e) {
            log.error("更新知识失败", e);
            throw new RuntimeException("更新知识失败: " + e.getMessage());
        }
    }

    /**
     * 验证知识
     */
    @Transactional
    public void validateKnowledge(Long knowledgeId, boolean isValid, String validationReason) {
        log.info("验证知识 {}，结果: {}", knowledgeId, isValid);
        
        try {
            KnowledgeBase knowledge = knowledgeBaseRepository.findById(knowledgeId)
                    .orElseThrow(() -> new RuntimeException("知识不存在"));
            
            if (isValid) {
                knowledge.setStatus(KnowledgeStatus.VALIDATED);
                knowledge.setConfidence(Math.min(1.0, knowledge.getConfidence() + 0.1));
                knowledge.setValidationCount(knowledge.getValidationCount() + 1);
            } else {
                knowledge.setStatus(KnowledgeStatus.DISPUTED);
                knowledge.setConfidence(Math.max(0.0, knowledge.getConfidence() - 0.2));
            }
            
            // 更新元数据
            Map<String, Object> metadata = parseMetadata(knowledge.getMetadata());
            metadata.put("last_validation", LocalDateTime.now());
            metadata.put("validation_reason", validationReason);
            knowledge.setMetadata(jsonUtils.toJson(metadata));
            
            knowledgeBaseRepository.save(knowledge);
            
            log.info("知识验证完成");
            
        } catch (Exception e) {
            log.error("验证知识失败", e);
        }
    }

    /**
     * 应用知识
     */
    @Transactional
    public KnowledgeApplication applyKnowledge(Long knowledgeId, Map<String, Object> applicationContext) {
        log.info("应用知识 {}", knowledgeId);
        
        try {
            KnowledgeBase knowledge = knowledgeBaseRepository.findById(knowledgeId)
                    .orElseThrow(() -> new RuntimeException("知识不存在"));
            
            // 更新使用统计
            knowledge.setUsageFrequency(knowledge.getUsageFrequency() + 1);
            knowledge.setLastUsedAt(LocalDateTime.now());
            
            // 评估应用结果
            boolean applicationSuccess = evaluateApplicationSuccess(applicationContext);
            
            if (applicationSuccess) {
                knowledge.setSuccessfulApplications(knowledge.getSuccessfulApplications() + 1);
                knowledge.setConfidence(Math.min(1.0, knowledge.getConfidence() + 0.05));
            } else {
                knowledge.setFailedApplications(knowledge.getFailedApplications() + 1);
                knowledge.setConfidence(Math.max(0.0, knowledge.getConfidence() - 0.1));
            }
            
            knowledgeBaseRepository.save(knowledge);
            
            KnowledgeApplication application = new KnowledgeApplication();
            application.setKnowledgeId(knowledgeId);
            application.setSuccess(applicationSuccess);
            application.setApplicationTime(LocalDateTime.now());
            application.setContext(jsonUtils.toJson(applicationContext));
            
            log.info("知识应用完成，成功: {}", applicationSuccess);
            return application;
            
        } catch (Exception e) {
            log.error("应用知识失败", e);
            throw new RuntimeException("应用知识失败: " + e.getMessage());
        }
    }

    /**
     * 维护知识库
     */
    @Transactional
    public KnowledgeMaintenanceResult maintainKnowledgeBase(Long lifeEntityId) {
        log.info("开始维护生命体 {} 的知识库", lifeEntityId);
        
        KnowledgeMaintenanceResult result = new KnowledgeMaintenanceResult();
        
        try {
            // 1. 清理过期知识
            int expiredCount = cleanupExpiredKnowledge(lifeEntityId);
            result.setExpiredKnowledgeCount(expiredCount);
            
            // 2. 更新知识状态
            int updatedCount = updateKnowledgeStatus(lifeEntityId);
            result.setUpdatedStatusCount(updatedCount);
            
            // 3. 重新评估知识重要性
            int reevaluatedCount = reevaluateKnowledgeImportance(lifeEntityId);
            result.setReevaluatedCount(reevaluatedCount);
            
            // 4. 建立新的知识关联
            int newRelationsCount = establishNewKnowledgeRelations(lifeEntityId);
            result.setNewRelationsCount(newRelationsCount);
            
            // 5. 识别知识缺口
            List<String> knowledgeGaps = identifyKnowledgeGaps(lifeEntityId);
            result.setKnowledgeGaps(knowledgeGaps);
            
            result.setMaintenanceTime(LocalDateTime.now());
            result.setSuccess(true);
            
            log.info("知识库维护完成，过期: {}, 更新: {}, 重评: {}, 新关联: {}", 
                    expiredCount, updatedCount, reevaluatedCount, newRelationsCount);
            
        } catch (Exception e) {
            log.error("维护知识库失败", e);
            result.setSuccess(false);
            result.setErrorMessage(e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取知识统计
     */
    public KnowledgeStatistics getKnowledgeStatistics(Long lifeEntityId) {
        log.info("获取生命体 {} 的知识统计", lifeEntityId);
        
        try {
            KnowledgeStatistics stats = new KnowledgeStatistics();
            stats.setLifeEntityId(lifeEntityId);
            
            // 总知识数量
            List<KnowledgeBase> allKnowledge = knowledgeBaseRepository.findByLifeEntityId(lifeEntityId);
            stats.setTotalKnowledge(allKnowledge.size());
            
            // 按类型统计
            Map<KnowledgeType, Long> typeCount = allKnowledge.stream()
                    .collect(Collectors.groupingBy(KnowledgeBase::getKnowledgeType, Collectors.counting()));
            stats.setKnowledgeByType(typeCount);
            
            // 按状态统计
            Map<KnowledgeStatus, Long> statusCount = allKnowledge.stream()
                    .collect(Collectors.groupingBy(KnowledgeBase::getStatus, Collectors.counting()));
            stats.setKnowledgeByStatus(statusCount);
            
            // 平均置信度
            double avgConfidence = knowledgeBaseRepository.calculateAverageConfidence(lifeEntityId);
            stats.setAverageConfidence(avgConfidence);
            
            // 最常用知识
            List<KnowledgeBase> mostUsed = knowledgeBaseRepository.findFrequentlyUsedKnowledge(lifeEntityId, 5);
            stats.setMostUsedKnowledge(mostUsed);
            
            // 最重要知识
            List<KnowledgeBase> mostImportant = knowledgeBaseRepository.findImportantKnowledge(lifeEntityId, 0.8);
            stats.setMostImportantKnowledge(mostImportant);
            
            return stats;
            
        } catch (Exception e) {
            log.error("获取知识统计失败", e);
            return new KnowledgeStatistics();
        }
    }

    // 私有辅助方法

    private KnowledgeBase extractProceduralKnowledge(LearningExperience experience) {
        if (experience.getLearningContent() == null || experience.getLearningContent().isEmpty()) {
            return null;
        }
        
        KnowledgeBase knowledge = new KnowledgeBase();
        knowledge.setLifeEntityId(experience.getLifeEntityId());
        knowledge.setKnowledgeType(KnowledgeType.PROCEDURAL);
        knowledge.setTitle("程序性知识：" + experience.getTitle());
        knowledge.setContent(experience.getLearningContent());
        knowledge.setSummary("从经验中提取的程序性知识");
        knowledge.setStatus(KnowledgeStatus.LEARNING);
        knowledge.setConfidence(experience.getEfficiency());
        knowledge.setImportance(experience.getImportanceScore());
        knowledge.setSourceExperienceId(experience.getId());
        knowledge.setSource("learning_experience");
        knowledge.setDepthLevel(experience.getDifficultyLevel());
        knowledge.setAbstractionLevel(0.3); // 程序性知识抽象程度较低
        
        return knowledge;
    }

    private KnowledgeBase extractConceptualKnowledge(LearningExperience experience) {
        // 只有某些类型的经验才能提取概念性知识
        if (experience.getExperienceType().name().contains("LEARNING") || 
            experience.getExperienceType().name().contains("INNOVATION")) {
            
            KnowledgeBase knowledge = new KnowledgeBase();
            knowledge.setLifeEntityId(experience.getLifeEntityId());
            knowledge.setKnowledgeType(KnowledgeType.CONCEPTUAL);
            knowledge.setTitle("概念性知识：" + experience.getTitle());
            knowledge.setContent(experience.getDescription());
            knowledge.setSummary("从经验中提取的概念性理解");
            knowledge.setStatus(KnowledgeStatus.LEARNING);
            knowledge.setConfidence(experience.getEfficiency() * 0.8);
            knowledge.setImportance(experience.getImportanceScore());
            knowledge.setSourceExperienceId(experience.getId());
            knowledge.setSource("learning_experience");
            knowledge.setDepthLevel(Math.min(10, experience.getDifficultyLevel() + 2));
            knowledge.setAbstractionLevel(0.7); // 概念性知识抽象程度较高
            
            return knowledge;
        }
        
        return null;
    }

    private KnowledgeBase extractStrategicKnowledge(LearningExperience experience) {
        // 从决策和问题解决经验中提取策略性知识
        if (experience.getExperienceType().name().contains("DECISION") || 
            experience.getExperienceType().name().contains("PROBLEM")) {
            
            KnowledgeBase knowledge = new KnowledgeBase();
            knowledge.setLifeEntityId(experience.getLifeEntityId());
            knowledge.setKnowledgeType(KnowledgeType.STRATEGIC);
            knowledge.setTitle("策略性知识：" + experience.getTitle());
            knowledge.setContent("策略：" + experience.getLearningContent());
            knowledge.setSummary("从决策经验中提取的策略性知识");
            knowledge.setStatus(KnowledgeStatus.LEARNING);
            knowledge.setConfidence(experience.getEfficiency());
            knowledge.setImportance(experience.getImportanceScore() * 1.2); // 策略性知识通常更重要
            knowledge.setSourceExperienceId(experience.getId());
            knowledge.setSource("learning_experience");
            knowledge.setDepthLevel(experience.getDifficultyLevel());
            knowledge.setAbstractionLevel(0.6);
            
            return knowledge;
        }
        
        return null;
    }

    private KnowledgeBase extractConditionalKnowledge(LearningExperience experience) {
        if (experience.getContext() != null && !experience.getContext().isEmpty()) {
            KnowledgeBase knowledge = new KnowledgeBase();
            knowledge.setLifeEntityId(experience.getLifeEntityId());
            knowledge.setKnowledgeType(KnowledgeType.CONDITIONAL);
            knowledge.setTitle("条件性知识：" + experience.getTitle());
            knowledge.setContent("在" + experience.getContext() + "条件下：" + experience.getLearningContent());
            knowledge.setSummary("从经验中提取的条件性知识");
            knowledge.setStatus(KnowledgeStatus.LEARNING);
            knowledge.setConfidence(experience.getEfficiency() * 0.9);
            knowledge.setImportance(experience.getImportanceScore());
            knowledge.setSourceExperienceId(experience.getId());
            knowledge.setSource("learning_experience");
            knowledge.setDepthLevel(experience.getDifficultyLevel());
            knowledge.setAbstractionLevel(0.5);
            
            return knowledge;
        }
        
        return null;
    }

    private KnowledgeType parseKnowledgeType(Map<String, Object> data) {
        String typeStr = (String) data.get("knowledge_type");
        if (typeStr != null) {
            try {
                return KnowledgeType.valueOf(typeStr.toUpperCase());
            } catch (IllegalArgumentException e) {
                log.warn("未知的知识类型: {}", typeStr);
            }
        }
        return KnowledgeType.FACTUAL; // 默认类型
    }

    private Double parseDouble(Map<String, Object> data, String key, Double defaultValue) {
        Object value = data.get(key);
        if (value instanceof Number) {
            return ((Number) value).doubleValue();
        }
        return defaultValue;
    }

    private Integer parseInt(Map<String, Object> data, String key, Integer defaultValue) {
        Object value = data.get(key);
        if (value instanceof Number) {
            return ((Number) value).intValue();
        }
        return defaultValue;
    }

    private Map<String, Object> createKnowledgeMetadata(Map<String, Object> knowledgeData) {
        Map<String, Object> metadata = new HashMap<>();
        metadata.put("created_by", "knowledge_management_service");
        metadata.put("created_at", LocalDateTime.now());
        metadata.put("extraction_method", "manual");
        return metadata;
    }

    private Map<String, Object> parseMetadata(String metadataJson) {
        try {
            return jsonUtils.fromJson(metadataJson, Map.class);
        } catch (Exception e) {
            return new HashMap<>();
        }
    }

    private void establishKnowledgeRelations(KnowledgeBase knowledge) {
        // 查找相关知识
        List<KnowledgeBase> relatedKnowledge = knowledgeBaseRepository
                .findByLifeEntityIdAndCategory(knowledge.getLifeEntityId(), knowledge.getCategory());
        
        if (relatedKnowledge.size() > 1) {
            List<String> relatedIds = relatedKnowledge.stream()
                    .filter(k -> !k.getId().equals(knowledge.getId()))
                    .map(k -> k.getId().toString())
                    .limit(5)
                    .collect(Collectors.toList());
            
            if (!relatedIds.isEmpty()) {
                knowledge.setRelatedKnowledgeIds(String.join(",", relatedIds));
                knowledgeBaseRepository.save(knowledge);
            }
        }
    }

    private List<KnowledgeBase> applySearchCriteria(List<KnowledgeBase> results, KnowledgeSearchCriteria criteria) {
        return results.stream()
                .filter(k -> criteria.getKnowledgeType() == null || k.getKnowledgeType() == criteria.getKnowledgeType())
                .filter(k -> criteria.getStatus() == null || k.getStatus() == criteria.getStatus())
                .filter(k -> criteria.getMinConfidence() == null || k.getConfidence() >= criteria.getMinConfidence())
                .filter(k -> criteria.getMinImportance() == null || k.getImportance() >= criteria.getMinImportance())
                .collect(Collectors.toList());
    }

    private List<KnowledgeBase> sortByRelevance(List<KnowledgeBase> results, String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            // 按重要性和使用频率排序
            return results.stream()
                    .sorted(Comparator.comparing(KnowledgeBase::getImportance)
                            .thenComparing(KnowledgeBase::getUsageFrequency)
                            .reversed())
                    .collect(Collectors.toList());
        }
        
        // 按关键词相关性排序（简化实现）
        return results.stream()
                .sorted((k1, k2) -> {
                    int score1 = calculateRelevanceScore(k1, keyword);
                    int score2 = calculateRelevanceScore(k2, keyword);
                    return Integer.compare(score2, score1);
                })
                .collect(Collectors.toList());
    }

    private int calculateRelevanceScore(KnowledgeBase knowledge, String keyword) {
        int score = 0;
        String lowerKeyword = keyword.toLowerCase();
        
        if (knowledge.getTitle() != null && knowledge.getTitle().toLowerCase().contains(lowerKeyword)) {
            score += 10;
        }
        if (knowledge.getSummary() != null && knowledge.getSummary().toLowerCase().contains(lowerKeyword)) {
            score += 5;
        }
        if (knowledge.getContent() != null && knowledge.getContent().toLowerCase().contains(lowerKeyword)) {
            score += 3;
        }
        if (knowledge.getTags() != null && knowledge.getTags().toLowerCase().contains(lowerKeyword)) {
            score += 7;
        }
        
        return score;
    }

    private boolean shouldCreateNewVersion(KnowledgeBase knowledge, Map<String, Object> updateData) {
        // 如果内容有重大变化，创建新版本
        String newContent = (String) updateData.get("content");
        if (newContent != null && !newContent.equals(knowledge.getContent())) {
            return true;
        }
        
        return false;
    }

    private KnowledgeBase createNewKnowledgeVersion(KnowledgeBase originalKnowledge, Map<String, Object> updateData) {
        KnowledgeBase newVersion = new KnowledgeBase();
        
        // 复制原有属性
        newVersion.setLifeEntityId(originalKnowledge.getLifeEntityId());
        newVersion.setKnowledgeType(originalKnowledge.getKnowledgeType());
        newVersion.setTitle(originalKnowledge.getTitle());
        newVersion.setCategory(originalKnowledge.getCategory());
        newVersion.setParentKnowledgeId(originalKnowledge.getId());
        newVersion.setKnowledgeVersion(originalKnowledge.getKnowledgeVersion() + 1);
        
        // 应用更新
        updateKnowledgeFields(newVersion, updateData);
        
        // 归档旧版本
        originalKnowledge.setStatus(KnowledgeStatus.ARCHIVED);
        knowledgeBaseRepository.save(originalKnowledge);
        
        return knowledgeBaseRepository.save(newVersion);
    }

    private void updateKnowledgeFields(KnowledgeBase knowledge, Map<String, Object> updateData) {
        if (updateData.containsKey("content")) {
            knowledge.setContent((String) updateData.get("content"));
        }
        if (updateData.containsKey("summary")) {
            knowledge.setSummary((String) updateData.get("summary"));
        }
        if (updateData.containsKey("tags")) {
            knowledge.setTags((String) updateData.get("tags"));
        }
        if (updateData.containsKey("importance")) {
            knowledge.setImportance(parseDouble(updateData, "importance", knowledge.getImportance()));
        }
        if (updateData.containsKey("confidence")) {
            knowledge.setConfidence(parseDouble(updateData, "confidence", knowledge.getConfidence()));
        }
    }

    private void reevaluateKnowledge(KnowledgeBase knowledge) {
        // 基于使用频率和成功率重新评估重要性
        if (knowledge.getUsageFrequency() > 0) {
            double successRate = (double) knowledge.getSuccessfulApplications() / 
                    (knowledge.getSuccessfulApplications() + knowledge.getFailedApplications());
            
            double newImportance = (knowledge.getImportance() + successRate + 
                    Math.min(knowledge.getUsageFrequency() / 100.0, 0.3)) / 3.0;
            
            knowledge.setImportance(Math.min(1.0, newImportance));
        }
    }

    private boolean evaluateApplicationSuccess(Map<String, Object> applicationContext) {
        // 简化的成功评估
        Object successObj = applicationContext.get("success");
        if (successObj instanceof Boolean) {
            return (Boolean) successObj;
        }
        
        // 默认假设成功
        return true;
    }

    private int cleanupExpiredKnowledge(Long lifeEntityId) {
        List<KnowledgeBase> expiredKnowledge = knowledgeBaseRepository.findExpiredKnowledge(lifeEntityId, LocalDateTime.now());
        
        for (KnowledgeBase knowledge : expiredKnowledge) {
            knowledge.setStatus(KnowledgeStatus.OUTDATED);
        }
        
        if (!expiredKnowledge.isEmpty()) {
            knowledgeBaseRepository.saveAll(expiredKnowledge);
        }
        
        return expiredKnowledge.size();
    }

    private int updateKnowledgeStatus(Long lifeEntityId) {
        List<KnowledgeBase> needingValidation = knowledgeBaseRepository.findKnowledgeNeedingValidation(lifeEntityId);
        
        int updatedCount = 0;
        for (KnowledgeBase knowledge : needingValidation) {
            // 如果知识长时间未验证，自动设为需要更新
            if (knowledge.getCreatedAt().isBefore(LocalDateTime.now().minus(30, ChronoUnit.DAYS))) {
                knowledge.setStatus(KnowledgeStatus.NEEDS_UPDATE);
                knowledgeBaseRepository.save(knowledge);
                updatedCount++;
            }
        }
        
        return updatedCount;
    }

    private int reevaluateKnowledgeImportance(Long lifeEntityId) {
        List<KnowledgeBase> allKnowledge = knowledgeBaseRepository.findByLifeEntityId(lifeEntityId);
        
        int reevaluatedCount = 0;
        for (KnowledgeBase knowledge : allKnowledge) {
            double oldImportance = knowledge.getImportance();
            reevaluateKnowledge(knowledge);
            
            if (Math.abs(knowledge.getImportance() - oldImportance) > 0.1) {
                knowledgeBaseRepository.save(knowledge);
                reevaluatedCount++;
            }
        }
        
        return reevaluatedCount;
    }

    private int establishNewKnowledgeRelations(Long lifeEntityId) {
        List<KnowledgeBase> allKnowledge = knowledgeBaseRepository.findByLifeEntityId(lifeEntityId);
        
        int newRelationsCount = 0;
        for (KnowledgeBase knowledge : allKnowledge) {
            if (knowledge.getRelatedKnowledgeIds() == null || knowledge.getRelatedKnowledgeIds().isEmpty()) {
                establishKnowledgeRelations(knowledge);
                if (knowledge.getRelatedKnowledgeIds() != null && !knowledge.getRelatedKnowledgeIds().isEmpty()) {
                    newRelationsCount++;
                }
            }
        }
        
        return newRelationsCount;
    }

    private List<String> identifyKnowledgeGaps(Long lifeEntityId) {
        List<String> gaps = new ArrayList<>();
        
        // 分析知识类型分布
        Map<KnowledgeType, Long> typeCount = knowledgeBaseRepository.findByLifeEntityId(lifeEntityId)
                .stream()
                .collect(Collectors.groupingBy(KnowledgeBase::getKnowledgeType, Collectors.counting()));
        
        // 检查缺失的知识类型
        for (KnowledgeType type : KnowledgeType.values()) {
            if (typeCount.getOrDefault(type, 0L) == 0) {
                gaps.add("缺少" + type.getDescription() + "类型的知识");
            }
        }
        
        return gaps;
    }

    // 内部数据类
    public static class KnowledgeSearchCriteria {
        private KnowledgeType knowledgeType;
        private KnowledgeStatus status;
        private Double minConfidence;
        private Double minImportance;
        private String category;
        private String tag;

        // getters and setters
        public KnowledgeType getKnowledgeType() { return knowledgeType; }
        public void setKnowledgeType(KnowledgeType knowledgeType) { this.knowledgeType = knowledgeType; }
        public KnowledgeStatus getStatus() { return status; }
        public void setStatus(KnowledgeStatus status) { this.status = status; }
        public Double getMinConfidence() { return minConfidence; }
        public void setMinConfidence(Double minConfidence) { this.minConfidence = minConfidence; }
        public Double getMinImportance() { return minImportance; }
        public void setMinImportance(Double minImportance) { this.minImportance = minImportance; }
        public String getCategory() { return category; }
        public void setCategory(String category) { this.category = category; }
        public String getTag() { return tag; }
        public void setTag(String tag) { this.tag = tag; }
    }

    public static class KnowledgeApplication {
        private Long knowledgeId;
        private boolean success;
        private LocalDateTime applicationTime;
        private String context;

        // getters and setters
        public Long getKnowledgeId() { return knowledgeId; }
        public void setKnowledgeId(Long knowledgeId) { this.knowledgeId = knowledgeId; }
        public boolean isSuccess() { return success; }
        public void setSuccess(boolean success) { this.success = success; }
        public LocalDateTime getApplicationTime() { return applicationTime; }
        public void setApplicationTime(LocalDateTime applicationTime) { this.applicationTime = applicationTime; }
        public String getContext() { return context; }
        public void setContext(String context) { this.context = context; }
    }

    public static class KnowledgeMaintenanceResult {
        private int expiredKnowledgeCount;
        private int updatedStatusCount;
        private int reevaluatedCount;
        private int newRelationsCount;
        private List<String> knowledgeGaps;
        private LocalDateTime maintenanceTime;
        private boolean success;
        private String errorMessage;

        // getters and setters
        public int getExpiredKnowledgeCount() { return expiredKnowledgeCount; }
        public void setExpiredKnowledgeCount(int expiredKnowledgeCount) { this.expiredKnowledgeCount = expiredKnowledgeCount; }
        public int getUpdatedStatusCount() { return updatedStatusCount; }
        public void setUpdatedStatusCount(int updatedStatusCount) { this.updatedStatusCount = updatedStatusCount; }
        public int getReevaluatedCount() { return reevaluatedCount; }
        public void setReevaluatedCount(int reevaluatedCount) { this.reevaluatedCount = reevaluatedCount; }
        public int getNewRelationsCount() { return newRelationsCount; }
        public void setNewRelationsCount(int newRelationsCount) { this.newRelationsCount = newRelationsCount; }
        public List<String> getKnowledgeGaps() { return knowledgeGaps; }
        public void setKnowledgeGaps(List<String> knowledgeGaps) { this.knowledgeGaps = knowledgeGaps; }
        public LocalDateTime getMaintenanceTime() { return maintenanceTime; }
        public void setMaintenanceTime(LocalDateTime maintenanceTime) { this.maintenanceTime = maintenanceTime; }
        public boolean isSuccess() { return success; }
        public void setSuccess(boolean success) { this.success = success; }
        public String getErrorMessage() { return errorMessage; }
        public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; }
    }

    public static class KnowledgeStatistics {
        private Long lifeEntityId;
        private int totalKnowledge;
        private Map<KnowledgeType, Long> knowledgeByType;
        private Map<KnowledgeStatus, Long> knowledgeByStatus;
        private double averageConfidence;
        private List<KnowledgeBase> mostUsedKnowledge;
        private List<KnowledgeBase> mostImportantKnowledge;

        // getters and setters
        public Long getLifeEntityId() { return lifeEntityId; }
        public void setLifeEntityId(Long lifeEntityId) { this.lifeEntityId = lifeEntityId; }
        public int getTotalKnowledge() { return totalKnowledge; }
        public void setTotalKnowledge(int totalKnowledge) { this.totalKnowledge = totalKnowledge; }
        public Map<KnowledgeType, Long> getKnowledgeByType() { return knowledgeByType; }
        public void setKnowledgeByType(Map<KnowledgeType, Long> knowledgeByType) { this.knowledgeByType = knowledgeByType; }
        public Map<KnowledgeStatus, Long> getKnowledgeByStatus() { return knowledgeByStatus; }
        public void setKnowledgeByStatus(Map<KnowledgeStatus, Long> knowledgeByStatus) { this.knowledgeByStatus = knowledgeByStatus; }
        public double getAverageConfidence() { return averageConfidence; }
        public void setAverageConfidence(double averageConfidence) { this.averageConfidence = averageConfidence; }
        public List<KnowledgeBase> getMostUsedKnowledge() { return mostUsedKnowledge; }
        public void setMostUsedKnowledge(List<KnowledgeBase> mostUsedKnowledge) { this.mostUsedKnowledge = mostUsedKnowledge; }
        public List<KnowledgeBase> getMostImportantKnowledge() { return mostImportantKnowledge; }
        public void setMostImportantKnowledge(List<KnowledgeBase> mostImportantKnowledge) { this.mostImportantKnowledge = mostImportantKnowledge; }
    }etters
        public KnowledgeType getKnowledgeType() { return knowledgeType; }
        public void setKnowledgeType(KnowledgeType knowledgeType) { this.knowledgeType = knowledgeType; }
        public KnowledgeStatus getStatus() { return status; }
        public void setStatus(KnowledgeStatus status) { this.status = status; }
        public Double getMinConfidence() { return minConfidence; }
        public void setMinConfidence(Double minConfidence) { this.minConfidence = minConfidence; }
        public Double getMinImportance() { return minImportance; }
        public void setMinImportance(Double minImportance) { this.minImportance = minImportance; }
        public String getCategory() { return category; }
        public void setCategory(String category) { this.category = category; }
        public String getTag() { return tag; }
        public void setTag(String tag) { this.tag = tag; }
    }

    public static class KnowledgeApplication {
        private Long knowledgeId;
        private boolean success;
        private LocalDateTime applicationTime;
        private String context;

        // getters and setters
        public Long getKnowledgeId() { return knowledgeId; }
        public void setKnowledgeId(Long knowledgeId) { this.knowledgeId = knowledgeId; }
        public boolean isSuccess() { return success; }
        public void setSuccess(boolean success) { this.success = success; }
        public LocalDateTime getApplicationTime() { return applicationTime; }
        public void setApplicationTime(LocalDateTime applicationTime) { this.applicationTime = applicationTime; }
        public String getContext() { return context; }
        public void setContext(String context) { this.context = context; }
    }

    public static class KnowledgeMaintenanceResult {
        private boolean success;
        private String errorMessage;
        private LocalDateTime maintenanceTime;
        private int expiredKnowledgeCount;
        private int updatedStatusCount;
        private int reevaluatedCount;
        private int newRelationsCount;
        private List<String> knowledgeGaps = new ArrayList<>();

        // getters and setters
        public boolean isSuccess() { return success; }
        public void setSuccess(boolean success) { this.success = success; }
        public String getErrorMessage() { return errorMessage; }
        public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; }
        public LocalDateTime getMaintenanceTime() { return maintenanceTime; }
        public void setMaintenanceTime(LocalDateTime maintenanceTime) { this.maintenanceTime = maintenanceTime; }
        public int getExpiredKnowledgeCount() { return expiredKnowledgeCount; }
        public void setExpiredKnowledgeCount(int expiredKnowledgeCount) { this.expiredKnowledgeCount = expiredKnowledgeCount; }
        public int getUpdatedStatusCount() { return updatedStatusCount; }
        public void setUpdatedStatusCount(int updatedStatusCount) { this.updatedStatusCount = updatedStatusCount; }
        public int getReevaluatedCount() { return reevaluatedCount; }
        public void setReevaluatedCount(int reevaluatedCount) { this.reevaluatedCount = reevaluatedCount; }
        public int getNewRelationsCount() { return newRelationsCount; }
        public void setNewRelationsCount(int newRelationsCount) { this.newRelationsCount = newRelationsCount; }
        public List<String> getKnowledgeGaps() { return knowledgeGaps; }
        public void setKnowledgeGaps(List<String> knowledgeGaps) { this.knowledgeGaps = knowledgeGaps; }
    }

    public static class KnowledgeStatistics {
        private Long lifeEntityId;
        private int totalKnowledge;
        private Map<KnowledgeType, Long> knowledgeByType = new HashMap<>();
        private Map<KnowledgeStatus, Long> knowledgeByStatus = new HashMap<>();
        private double averageConfidence;
        private List<KnowledgeBase> mostUsedKnowledge = new ArrayList<>();
        private List<KnowledgeBase> mostImportantKnowledge = new ArrayList<>();

        // getters and setters
        public Long getLifeEntityId() { return lifeEntityId; }
        public void setLifeEntityId(Long lifeEntityId) { this.lifeEntityId = lifeEntityId; }
        public int getTotalKnowledge() { return totalKnowledge; }
        public void setTotalKnowledge(int totalKnowledge) { this.totalKnowledge = totalKnowledge; }
        public Map<KnowledgeType, Long> getKnowledgeByType() { return knowledgeByType; }
        public void setKnowledgeByType(Map<KnowledgeType, Long> knowledgeByType) { this.knowledgeByType = knowledgeByType; }
        public Map<KnowledgeStatus, Long> getKnowledgeByStatus() { return knowledgeByStatus; }
        public void setKnowledgeByStatus(Map<KnowledgeStatus, Long> knowledgeByStatus) { this.knowledgeByStatus = knowledgeByStatus; }
        public double getAverageConfidence() { return averageConfidence; }
        public void setAverageConfidence(double averageConfidence) { this.averageConfidence = averageConfidence; }
        public List<KnowledgeBase> getMostUsedKnowledge() { return mostUsedKnowledge; }
        public void setMostUsedKnowledge(List<KnowledgeBase> mostUsedKnowledge) { this.mostUsedKnowledge = mostUsedKnowledge; }
        public List<KnowledgeBase> getMostImportantKnowledge() { return mostImportantKnowledge; }
        public void setMostImportantKnowledge(List<KnowledgeBase> mostImportantKnowledge) { this.mostImportantKnowledge = mostImportantKnowledge; }
    }
}